import React, { Component } from 'react';
import {
    Text,
    View,
    Image,
    TextInput,
    Animated,
    Switch,
    StyleSheet,
    RefreshControl,
    TouchableOpacity,
    DeviceEventEmitter,
    Dimensions,
    ScrollView,
    AsyncStorage,
    ActivityIndicator,
} from 'react-native';
import { Actions } from 'react-native-router-flux';
import DeviceUtils from '../utils/DeviceUtils';
import { StyleUtils } from '../utils/StyleUtils';
import ActionCodes from '../config/ActionCodes';
import actioncoll from '../actions'
import {connect} from 'react-redux'

class login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            fadeInOpacity: new Animated.Value(1),
            tmpName: 'admin',
            tmpPsw: '205',
            switchType: true,
            loadedEd: false,
            userData: {
                tokenId: '我是 tokenId',
                userId: '我是 userId'
            }
        }

    }

    componentDidMount() {

    }

    componentWillUnmount() {

    }


    render() {
        return (
            <ScrollView style={{ flex: 1 }}
                scrollEnabled={false}
                showsVerticalScrollIndicator={false}
                keyboardShouldPersistTaps='handled'>


                <Animated.View style={[styles.container, { opacity: this.state.fadeInOpacity }]}>
                    {this._login()}
                </Animated.View>



            </ScrollView>
        )
    }

    _login() {
        return (
            <View style={styles.BGImage}>

                <Image style={styles.logoImage} />

                <View style={styles.userNameView}>
                    <Text style={styles.textStyle}>用户名</Text>
                    <TextInput style={styles.textInputView}
                        placeholder={'请输入用户名'}
                        editable={true}
                        autoCapitalize={'none'}
                        defaultValue={this.state.tmpName}
                        keyboardType={'numeric'}
                        underlineColorAndroid={'transparent'}
                        placeholderTextColor={'#fff'}
                        multiline={false}
                        onBlur={() => this._onBlur()}
                        textAlign="center"
                        onChangeText={(text) => {
                            this.setState({
                                tmpName: text
                            });
                        }} />

                </View>
                <View style={[styles.userNameView, { marginTop: DeviceUtils.deviceWidth / 10 }]}>
                    <Text style={styles.textStyle}>{'密     码'}</Text>
                    <TextInput style={styles.textInputView}
                        placeholder={'请输入密码'}
                        keyboardType={'default'}
                        defaultValue={this.state.tmpPsw}
                        underlineColorAndroid={'transparent'}
                        placeholderTextColor={'#fff'}
                        multiline={false}
                        secureTextEntry={true}
                        textAlign='center'
                        onChangeText={(psw) => {
                            this.setState({
                                tmpPsw: psw
                            })
                        }} />

                </View>
                <View style={styles.switch}>
                    <Text style={styles.textStyle}>自动登入</Text>
                    <Switch value={this.state.switchType}
                        onValueChange={(value) => {
                            this._changeSate(value)
                        }} />
                </View>

                {this._longType()}

                <View style={styles.footerView}>
                    <TouchableOpacity onPress={() => this._register()}>
                        <Text style={styles.footerText}>注册账号</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => this._forgetPwd()}>
                        <Text style={styles.footerText}>忘记密码</Text>
                    </TouchableOpacity>
                </View>




            </View>
        )
    }

    _longType() {
        const { tmpName, tmpPsw } = this.state;
        if ((tmpName && tmpPsw) || (tmpName.trim().length !== 0 && tmpPsw.trim().length !== 0)) {
            return (
                <TouchableOpacity style={styles.loginView}
                    onPress={() => this._loginClick()}>
                    <Text style={styles.loginText}>{'登              入'}</Text>
                    <ActivityIndicator
                        animating={this.props.isLoading.login}
                        style={[styles.centering]}
                        size="small"
                    />
                </TouchableOpacity>
            )
        } else {
            return (
                <View style={[styles.loginView, { backgroundColor: 'rgba(128,128,128,0.5)' }]}>
                    <Text style={styles.loginText}>{'登              入'}</Text>

                </View>
            )
        }
    }

    _onBlur() {

    }

    _loginClick() {

        this.props.LOGIN(this.state.tmpName, this.state.tmpPsw);

        // let params = { LOGON_NAME: this.state.tmpName, PASSWORD: this.state.tmpPsw };

        // postFetch(ActionCodes.login, params)
        //     .then(res => {
        //         Session.Token = res.TokenGuid;
        //         Session.CurrentUser = res;
        //         Actions.replace('tabbar');
        //     })

        //

        // AsyncStorage.setItem('islogin', 'true', (error) => {
        //     if (!error) {
        //         Actions.replace('tabbar');
        //     }
        // })
        if (!(/^1[34578]\d{9}$/.test(this.state.tmpName))) {
            //Alert.alert('手机号码错误', '你输入的是一个无效的手机号码', [{ text: '确定' }])
        } else {
            //登录接口，成功后到下个页面
            //this.fetchDate()
        }
    }

    _forgetPwd() {
        Actions.pop();
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    BGImage: {
        width: DeviceUtils.deviceWidth,
        height: DeviceUtils.deviceHeight,
        justifyContent: 'center',
        backgroundColor: StyleUtils.mainColor,
        alignItems: 'center',
    },
    logoImage: {
        height: DeviceUtils.deviceWidth / 2.5,
        width: DeviceUtils.deviceWidth / 2,
        borderRadius: 8,
        resizeMode: 'cover',
    },
    userNameView: {
        height: DeviceUtils.deviceHeight / 16,
        width: DeviceUtils.deviceWidth / 1.5,
        borderRadius: 3,
        backgroundColor: StyleUtils.backgroundColor1,
        marginTop: DeviceUtils.deviceWidth / 5,
        flexDirection: 'row',
        alignItems: 'center'
    },
    textInputView: {
        flex: 1,
        fontSize: 15,
        textAlignVertical: 'auto',
        color: StyleUtils.blue1,
        fontWeight: 'bold'
    },
    textStyle: {
        fontSize: 15,
        color: StyleUtils.blue1,
        marginLeft: 7,
        marginRight: 10,
        fontWeight: 'bold'
    },
    switch: {
        width: DeviceUtils.deviceWidth * 0.9,
        height: 35,
        flexDirection: 'row',
        justifyContent: 'flex-end',
        marginTop: 20,
        alignItems: 'center',
    },
    loginView: {
        width: 200,
        height: 45,
        backgroundColor: StyleUtils.blue1,
        borderRadius: 20,
        marginTop: DeviceUtils.deviceWidth / 14,
        alignItems: 'center',
        justifyContent: 'center',
    },
    loginText: {
        fontSize: 19,
        color: StyleUtils.white,
        fontWeight: 'bold'
    },
    footerView: {
        height: 40,
        width: DeviceUtils.deviceWidth * 0.9,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginTop: 20
    },
    footerText: {
        color: StyleUtils.white,
        fontSize: 17,
        fontWeight: 'bold'
    },
    obscure: {
        alignItems: 'center',
        justifyContent: 'center',
        width: DeviceUtils.deviceWidth,
        height: DeviceUtils.deviceHeight
    },
    centering: {
        position: 'absolute',
        top:2,
        left: 80,
        height: 40, 
        width: 40 
    },
});


    export default connect(
        (state) => ({
            isLoading: state.loginReducer.isLoading
        }),
        (dispatch) => ({
            LOGIN:(username, pwd)=> dispatch(actioncoll.login.LOGIN(username,pwd)),
        })
      )(login)